package org.ourguy.mymoviesandshows;

import java.util.ArrayList;
import java.util.Hashtable;

import org.ourguy.mymoviesandshows.adapters.ShowsAdapter;
import org.ourguy.mymoviesandshows.datamodel.ITitle;
import org.ourguy.mymoviesandshows.managers.DataAccessManager;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

public class SearchActivity extends ListActivity {
	
	private DataAccessManager menager;
	private AutoCompleteTextView searchText;
	private Hashtable<String, String> autoCompleteResults;
	private GetAutoCompleteTitlesAsync task = new GetAutoCompleteTitlesAsync();
	private ProgressBar progresBar;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_item_search);
		
		menager = DataAccessManager.getInstance(this);
		
		registerForContextMenu(getListView());
		
		progresBar = (ProgressBar)findViewById(R.id.progressBar);
		
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo == null || !netInfo.isConnectedOrConnecting()) {

			Toast.makeText(this, "No internet access!", Toast.LENGTH_LONG).show();
			finish();
		}
		
		getListView().setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				startTitleInfoActivity(position);
			}
		});
		
		searchText = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
		searchText.addTextChangedListener(new TextWatcher() {
			
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
			}
			
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				if(searchText.getText().length() > 2 && count == 0)
				{
					task.cancel(true);
					task = new GetAutoCompleteTitlesAsync();
					task.execute();
				}
			}
			
			public void afterTextChanged(Editable s) {
				
			}
		});
		
		Button serachButton = (Button)findViewById(R.id.searchButton);
		serachButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				search();
			}
		});
		
	}
	
	private void startTitleInfoActivity(int position) {
    	Intent intent = new Intent(getApplicationContext(), ShowActivity.class);
		ITitle show = (ITitle)getListAdapter().getItem(position);
    	intent.putExtra("show", show.getApiId());
		this.startActivity(intent);
    }
	
	private void search()
	{
		new FindShowAsync(this).execute();
	}
	
	@Override
    public boolean onContextItemSelected(MenuItem item) {
    	
        AdapterContextMenuInfo info =
        		(AdapterContextMenuInfo) item.getMenuInfo();
        
        switch (item.getItemId()) {
            case R.id.menuTitleInfo:
            	startTitleInfoActivity(info.position);
                return true;
            case R.id.menuRemoveFromTracking:
            	ITitle selected = (ITitle) getListAdapter().getItem(info.position);
            	if(selected.isInFavorites())
            		menager.removeFromFavorites(selected, SearchActivity.this);
            	else
            		menager.addToFavorites(selected, SearchActivity.this);
            	((ShowsAdapter)getListAdapter()).notifyDataSetChanged();
            	return true;
            default:
                return super.onContextItemSelected(item);
        }
    }
	
	@Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
        
        ITitle selected = (ITitle) getListAdapter().getItem(info.position);
        
        menu.setHeaderTitle(selected.getTitle());
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu_tracking_list, menu);
        
        if (selected.isInFavorites()) {
        	menu.findItem(R.id.menuRemoveFromTracking)
        			.setTitle("Remove from tracking list");
        } else {
        	menu.findItem(R.id.menuRemoveFromTracking)
        			.setTitle("Add to tracking list");
        }
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.menuTrackingList: {
			Intent intent = new Intent().setClass(getApplicationContext(),
					MyMoviesAndShowsActivity.class);
			intent.putExtra("tab", 0);
			this.startActivity(intent);
			return true;
		}
		case R.id.menuSchedule: {
			Intent intent = new Intent().setClass(getApplicationContext(),
					MyMoviesAndShowsActivity.class);
			intent.putExtra("tab", 2);
			this.startActivity(intent);
			return true;
		}
		case R.id.menuAbout: {
			Intent intent = new Intent().setClass(getApplicationContext(),
					AboutActivity.class);
			this.startActivity(intent);
			return true;
		}
		case R.id.menuSearch: {
			Intent intent = new Intent().setClass(getApplicationContext(),
					SearchActivity.class);
			this.startActivity(intent);
			return true;
		}
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	 private class GetAutoCompleteTitlesAsync extends AsyncTask<Void, Void, Boolean> {
	    
		 @Override
		protected void onPreExecute() {
			progresBar.setVisibility(View.VISIBLE);
			super.onPreExecute();
		}
		@Override
		protected Boolean doInBackground(Void... arg0) {
			try {
				autoCompleteResults = menager.autoCompleteSeries(searchText
						.getText().toString());
			} catch (Exception e) {
				return false;
			}
			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			if (success) {
				ArrayList<String> arr = new ArrayList<String>(autoCompleteResults.values());
				 ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
		                 android.R.layout.simple_dropdown_item_1line, arr);
		         searchText.setAdapter(adapter);
		         searchText.showDropDown();
		         searchText.refreshDrawableState();
		         progresBar.setVisibility(View.INVISIBLE);
			}
		}
	 }
	 
	 private class FindShowAsync extends AsyncTask<Void, Void, Boolean> {
		 private ArrayList<ITitle> titleList = new ArrayList<ITitle>();
		 private ListActivity activity;
		 private ProgressDialog dialog;

		 public FindShowAsync(ListActivity activity) {
			super();
			this.activity = activity;
			this.dialog = new ProgressDialog(activity);
		}
		 
		@Override
		protected void onPreExecute() {
			this.dialog.setMessage("Please wait until the search is finished.");
			this.dialog.setIndeterminate(true);
			this.dialog.show();
		}

		@Override
			protected Boolean doInBackground(Void... arg0) {
				try {
					titleList.addAll(menager.searchSeries(searchText.getText().toString()));
				} catch (Exception e) {
					return false;
				}
				return true;
			}

			@Override
			protected void onPostExecute(final Boolean success) {
				if (dialog.isShowing())
					dialog.hide();
				
				if (success) {
					ShowsAdapter adapter = new ShowsAdapter(activity, titleList);
					activity.setListAdapter(adapter);
				}
				else
				{
					Toast.makeText(activity, "Search failed!",
							Toast.LENGTH_LONG).show();

				}
			}
		 }
}
